package dbTest.daoImp;

import dbTest.Util.PrepareStatementUtil;
import dbTest.Entity.Dept;
import dbTest.Util.DBUtil;
import dbTest.dao.DeptDao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @Author: Tiangle
 * @Date: 2021/9/28 19:54
 */
public class DeptDaoImp implements DeptDao {
    @Override
    public boolean addDept(Dept d) {
        if (1== (int) PrepareStatementUtil.excute("insert into deptr values(default,?,?);",d.getName(),d.getAddress())){
            PrepareStatementUtil.close();
            DBUtil.close();
            return true;
        }
        return false;

    }

    @Override
    public boolean changeDept(Dept d) {
        if (1== (int)PrepareStatementUtil.excute("update deptr set name=?,address=? where id=?;",d.getName(),d.getAddress(),d.getId())){
            PrepareStatementUtil.close();
            DBUtil.close();
            return true;
        }
        return false;

    }

    @Override
    public boolean deleteDept(int id) {
        if (1== (int)PrepareStatementUtil.excute("delete from deptr where id=?;",id)){
            PrepareStatementUtil.close();
            DBUtil.close();
            return true;
        }
        return false;
    }

    @Override
    public Dept getDept(int id) {
        ResultSet excute = (ResultSet) PrepareStatementUtil.excute("select * from deptr where id=?;", id);
        Dept d = null;
        try {
            if (excute.next()){
                d = new Dept(excute.getInt(1),
                        excute.getString(2),
                        excute.getString(3));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        PrepareStatementUtil.close();
        DBUtil.close();
        return d;
    }

    @Override
    public ArrayList<Dept> getAll() {
        ResultSet excute = (ResultSet) PrepareStatementUtil.excute("select * from deptr;");
        ArrayList<Dept> al = new ArrayList<>();
        try {
            while (excute.next()){
                al.add(new Dept(excute.getInt(1),
                        excute.getString(2),
                        excute.getString(3)));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        PrepareStatementUtil.close();
        DBUtil.close();
        return al;
    }
}
